package com.mlamp.二叉树;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class 根节点到叶子节点路径和 {
    private List<List<Integer>> res = new ArrayList<>();



    public  static class TreeNode {
        int value;
        TreeNode left;
        TreeNode right;

        public TreeNode(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        根节点到叶子节点路径和 instance = new 根节点到叶子节点路径和();
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.right = new TreeNode(8);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.right = new TreeNode(5);
        instance.findPathsBySum(root, 22, new LinkedList<>());
        System.out.println(JSONObject.toJSONString(instance.res));
    }

    public void findPathsBySum(TreeNode root, int sum, LinkedList<TreeNode> path) {
        path.add(root);
        sum -= root.value;
        if (sum == 0 && root.left == null && root.right == null) {
            res.add(new ArrayList<>(path.stream().map(item -> item.value).collect(Collectors.toList())));
            return;
        }
        if (root.left != null) {
            findPathsBySum(root.left, sum, path);
            path.removeLast();
        }
        if (root.right != null) {
            findPathsBySum(root.right, sum, path);
            path.removeLast();
        }
    }
}
